package com.example.coffeeseller_2.model.helper.view_helper;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.MachineConfig.QRMsger;
import com.example.coffeeseller_2.model.beans.Coffee;
import com.example.coffeeseller_2.model.beans.Composition;
import com.example.coffeeseller_2.model.beans.DealRecorder;
import com.example.coffeeseller_2.model.beans.Step;
import com.example.coffeeseller_2.model.beans.TasteInfo;
import com.example.coffeeseller_2.model.factory.BuyState;
import com.example.coffeeseller_2.model.helper.TimeConstance;
import com.example.coffeeseller_2.model.helper.Trade;
import com.example.coffeeseller_2.model.listenner.OnSaomaTimeOutListenner;
import com.example.coffeeseller_2.model.listenner.OnTasteSelectedListenner;
import com.example.coffeeseller_2.utils.DensityUtil;
import com.example.coffeeseller_2.views.HomeActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.coffeeseller_2.model.factory.PayState.PAYED;

/**
 * Created by WH on 2018/8/12.
 * 支付界面左侧信息显示
 */

public class TradeLeftInfoViewHelper {

    private static String TAG = "TradeLeftInfoViewHelper";
    private View view;
    private LinearLayout mBackLayout;
    private TextView mBackTime;
    private TextView mCoffeeZhName;
    private TextView mCoffeeEnName;
    private TextView mCoffeeActivePrice;
    private TextView mCoffeePrice;
    private LinearLayout mDiscriptionLayout;
    private LinearLayout mTasteLayout;
    private LinearLayout mLeftPriceLayout;
    private TextView mCoffeeDispection;
    private LinearLayout mTasteContainer;

    private HomeActivity homeActivity;
    private Coffee coffee;
    private OnTasteSelectedListenner onTasteSelectedListenner;
    private Timer countTimeTimer;
    private TimerTask countTimeTimerTask;
    private Handler handler;
    private int timeCount = TimeConstance.COUNT_DOWN_TIME_LIMIT;
    private TextView mCoffeeTip;
    private OnSaomaTimeOutListenner onSaomaTimeOutListenner;

    private List<TasteHelper> tasteHelpers;
    private boolean haveTaste = false;

    public TradeLeftInfoViewHelper(HomeActivity homeActivity, Coffee coffee, OnTasteSelectedListenner onTasteSelectedListenner, LinearLayout parent) {
        this.homeActivity = homeActivity;
        this.coffee = coffee;
        this.onTasteSelectedListenner = onTasteSelectedListenner;
        view = LayoutInflater.from(homeActivity).inflate(R.layout.include_choose_info_left, parent, true);
        bindViews();
        initData();

    }

    /*
    * 如果倒计时显示最后10s,右侧二维码需要显示“扫码超时”
    * OnSaomaTimeOutListenner：扫码超时监听
    * */
    public void setTimeOutListenner(OnSaomaTimeOutListenner onSaomaTimeOutListenner) {
        this.onSaomaTimeOutListenner = onSaomaTimeOutListenner;
    }

    /*
    * 开始倒计时
    * */
    public void countDownTime() {

        timeCount = TimeConstance.COUNT_DOWN_TIME_LIMIT;
        stopCountTimer();

        if (countTimeTimer == null) {
            countTimeTimer = new Timer();
        }
        if (countTimeTimerTask == null) {
            countTimeTimerTask = new TimerTask() {
                @Override
                public void run() {

                    if (timeCount <= 0) {

                        backToChooseFrag();
                        countDownTimeClose();
                    } else {

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mBackTime.setText("（" + (timeCount) + "）");
                            }
                        });

                        if (DealRecorder.getInstance().getPayState() == PAYED) {

                            countDownTimeClose();
                        } else {

                            if (timeCount == 10 && onSaomaTimeOutListenner != null) {
                                onSaomaTimeOutListenner.timeOut();
                            }
                            timeCount--;
                        }
                    }
                }
            };
        }
        countTimeTimer.schedule(countTimeTimerTask, 0, 1000);
    }

    /*
    * 关闭倒计时
    * */
    public void countDownTimeClose() {

        stopCountTimer();
        handler.post(new Runnable() {
            @Override
            public void run() {

                mBackLayout.setVisibility(View.INVISIBLE);
            }
        });
        timeCount = TimeConstance.COUNT_DOWN_TIME_LIMIT;
    }

    /*
     * 扫码后，重置倒计时
     * */
    public void resetTimeCount() {
        this.timeCount = TimeConstance.COUNT_DOWN_TIME_LIMIT;
    }

    /*
     * 添加口味布局
     * */
    public void addToTasteContainer(final TasteInfo tasteInfo) {

        if (tasteInfo == null || tasteInfo.getTastes() == null || tasteInfo.getTastes().size() <= 0) {
            return;
        }
        if (haveTaste) {
            mTasteContainer.setVisibility(View.VISIBLE);
        } else {
            mTasteContainer.setVisibility(View.GONE);
        }
        TasteHelper tasteHelper = new TasteHelper(homeActivity, tasteInfo, coffee, onTasteSelectedListenner);
        tasteHelpers.add(tasteHelper);
        mTasteContainer.addView(tasteHelper.getView());
    }

    /*
    * 设置口味不能拖动
    * */
    public void setSeekbarEnable() {

        handler.post(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < tasteHelpers.size(); i++) {
                    TasteHelper tasteHelper = tasteHelpers.get(i);
                    tasteHelper.setSeekbarEnable();
                }
            }
        });
    }

    public void setBackInVisiable() {
        mBackLayout.setVisibility(View.INVISIBLE);
    }

    public View getView() {
        return view;
    }


    /*
    * 以下为私有方法
    * */
    private void initData() {
        handler = new Handler();
        if (coffee == null) return;
        tasteHelpers = new ArrayList<>();
        mBackTime.setText("（" + timeCount + "s）");
        mCoffeeZhName.setText(coffee.getName());
        if (!TextUtils.isEmpty(coffee.getEnName()) && !TextUtils.equals(coffee.getEnName(), "null")) {
            mCoffeeEnName.setText(coffee.getEnName());
        }

        if (!TextUtils.isEmpty(coffee.getTip()) && !TextUtils.equals(coffee.getTip(), "null")) {
            mCoffeeTip.setText(coffee.getTip());
            mCoffeeTip.setVisibility(View.VISIBLE);
        } else {
            mCoffeeTip.setVisibility(View.GONE);

        }
        Log.d(TAG, "getActivitiesPrice =" + coffee.getActivitiesPrice());
        Log.d(TAG, "getPrice =" + coffee.getPrice());
        mCoffeeDispection.setText(coffee.getDescribe());
        if (TextUtils.isEmpty(coffee.getActivitiesPrice())
                || TextUtils.equals(coffee.getActivitiesPrice(), "null")
                || Float.parseFloat(coffee.getActivitiesPrice()) <= 0) {
            mCoffeeActivePrice.setText(coffee.getPrice());
            mLeftPriceLayout.setVisibility(View.GONE);
        } else if (Float.parseFloat(coffee.getActivitiesPrice()) > 0) {
            mCoffeeActivePrice.setText(coffee.getActivitiesPrice());
            mCoffeePrice.setText(coffee.getPrice());
            mLeftPriceLayout.setVisibility(View.VISIBLE);
        }
        haveTaste = false;
        if (coffee != null && coffee.getStepList() != null && coffee.getStepList().size() > 0) {
            for (int i = 0; i < coffee.getStepList().size(); i++) {
                Step step = coffee.getStepList().get(i);
                if (step != null && step.getTastes().size() > 0) {
                    haveTaste = true;
                    break;
                }
            }
        }
      /*  if (haveTaste) {
            mTasteContainer.setVisibility(View.VISIBLE);
        } else {
            mTasteContainer.setVisibility(View.GONE);
        }*/
        addTasteProp();
    }

    private void bindViews() {

        mBackLayout = (LinearLayout) view.findViewById(R.id.backLayout);
        mBackTime = (TextView) view.findViewById(R.id.backTime);
        mCoffeeZhName = (TextView) view.findViewById(R.id.coffeeZhName);
        mCoffeeTip = (TextView) view.findViewById(R.id.coffeeTip);
        mCoffeeEnName = (TextView) view.findViewById(R.id.coffeeEnName);
        mCoffeeActivePrice = (TextView) view.findViewById(R.id.leftActivePrice);
        mCoffeePrice = (TextView) view.findViewById(R.id.leftPrice);
        mDiscriptionLayout = (LinearLayout) view.findViewById(R.id.discriptionLayout);
        mTasteLayout = (LinearLayout) view.findViewById(R.id.compLayout);
        mLeftPriceLayout = (LinearLayout) view.findViewById(R.id.leftPriceLayout);
        mCoffeeDispection = (TextView) view.findViewById(R.id.coffeeDispection);
        mTasteContainer = (LinearLayout) view.findViewById(R.id.tasteContainer);
        mTasteContainer.setVisibility(View.GONE);
        mBackLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backToChooseFrag();
                Trade.getInstance().stopTaskCheckPay();
            }
        });
    }

    /*
    * 返回，并关闭订单
    * */
    private void backToChooseFrag() {

        countDownTimeClose();
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (DealRecorder.getInstance().getPayState() == PAYED) {

                    Log.d(TAG, "backToChooseFrag true");
                    homeActivity.backToChooseFrag(true);
                } else {

                    Log.d(TAG, "backToChooseFrag false");
                    homeActivity.backToChooseFrag(false);
                }
                //关闭订单
                if (DealRecorder.getInstance().getBuyState() == BuyState.ALIPAY_WECHAT_BUY) {

                    if (!TextUtils.isEmpty(DealRecorder.getInstance().getOrder())) {
                        Trade.getInstance().closeTrade(DealRecorder.getInstance().getOrder());
                    }
                } else if (DealRecorder.getInstance().getBuyState() == BuyState.QUBEIMA_BUY) {
                    //如果是取杯码返回，上报交易结果给服务器

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            QRMsger qrMsger = new QRMsger();
                            DealRecorder.getInstance().setMakeSuccess(false);
                            DealRecorder.getInstance().setErrCode(homeActivity.getString(R.string.costom_return_qubeima));
                            DealRecorder newDealRecorder = qrMsger.reportTradeToServer(DealRecorder.getInstance(), "");
                        }
                    }).start();

                }

            }
        });

    }

    private void stopCountTimer() {

        if (countTimeTimer != null) {
            countTimeTimer.cancel();
            countTimeTimer = null;
            timeCount = TimeConstance.COUNT_DOWN_TIME_LIMIT;
        }
        countTimeTimerTask = null;
    }

    /*
    * 添加咖啡成分布局
    * */
    private void addTasteProp() {

        List<Composition> compositions = coffee.getComposition();

        Log.d(TAG, "compositions= " + compositions);

        if (compositions != null && compositions.size() > 0) {
            int totalWidth = DensityUtil.dp2px(homeActivity, homeActivity.getResources().getDimension(R.dimen.propertion_width));
            int totalHeight = DensityUtil.dp2px(homeActivity
                    , homeActivity.getResources().getDimension(R.dimen.propertion_height))
                    - DensityUtil.dp2px(homeActivity, 1f);

            for (int i = 0; i < compositions.size(); i++) {
                Composition composition = compositions.get(i);

                float proportion = 0;
                if (TextUtils.isEmpty(composition.getProportion())) {
                    proportion = 0;
                } else {
                    proportion = Float.parseFloat(composition.getProportion()) / 100;
                }
                Log.d(TAG, "proportion= " + proportion);

                int height = ((i + 1 == compositions.size()) && (proportion >= 100)) ? ViewGroup.LayoutParams.MATCH_PARENT
                        : (int) (totalHeight * proportion);

                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                        , height);
                params.gravity = Gravity.CENTER;
                TextView textView = new TextView(homeActivity);
                textView.setTextSize(12);
                textView.setText(composition.getName());
                textView.setTextColor(Color.parseColor(composition.getTextColor()));
                textView.setGravity(Gravity.CENTER);
                GradientDrawable drawable = new GradientDrawable();

                int radius = DensityUtil.dp2px(homeActivity, 1.4f);
                if (compositions.size() == 1) {

                    drawable.setCornerRadii(getCornerFloats(radius, radius, radius, radius));
                } else if (i == 0) {

                    drawable.setCornerRadii(getCornerFloats(radius, radius, 0, 0));
                } else if (i + 1 == compositions.size()) {

                    drawable.setCornerRadii(getCornerFloats(0, 0, radius, radius));
                }
                drawable.setStroke(1, Color.parseColor(composition.getBgColor()));
                drawable.setColor(Color.parseColor(composition.getBgColor()));
//                textView.setBackgroundDrawable(drawable);
                textView.setBackground(drawable);

                textView.setLayoutParams(params);

                mTasteLayout.addView(textView);
            }

        }
    }

    private float[] getCornerFloats(float leftTop, int rightTop, int rightBottom, int leftBottom) {
        return new float[]{
                leftTop, leftTop, rightTop, rightTop, rightBottom, rightBottom, leftBottom, leftBottom
        };
    }
}
